package com.spider.parsers;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.spider.beans.Offer;
import com.spider.utils.HttpUtils;
import com.spider.utils.StringUtils;
import com.spider.values.AliSortType;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AliParser {
    /**
     * 请求地址
     */
    private static final String REQUEST_PATH = "https://search.1688.com/service/marketOfferResultViewService";

    /**
     * 请求的每页索引，从0开始，每次递增20<br/>0、20、40
     */
    private int startIndex = 0;

    public List<Offer> getAll(String keyword, int pageNum, double priceStart, double priceEnd, AliSortType aliSortType) {
        List<Offer> offers = new ArrayList<>();
        while (startIndex != 60) {
            offers.addAll(parseData(keyword, pageNum, priceStart, priceEnd, aliSortType));
        }

        System.out.println("第" + pageNum + "页数据获取完成");
        return offers;
    }

    /**
     * 获取1688数据
     *
     * @param keyword   关键字
     * @param pageNum 页码
     * @param priceStart    最低价
     * @param priceEnd  最高价
     * @param aliSortType   排序方式{@link AliSortType}
     * @return  {@link Offer}List
     */
    private List<Offer> parseData(String keyword, int pageNum, double priceStart, double priceEnd, AliSortType aliSortType) {
        try {
            keyword = URLEncoder.encode(keyword, "gbk");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Map<String, String> params = new HashMap<>();
        params.put("spm", "a26352.13672862.filtbar.7.7a013fcdNwO3ac");
        params.put("keywords", keyword);
        params.put("n", "y");
        params.put("netType", "16");
        params.put("sortType", aliSortType.value);
        params.put("descendOrder", "true");
        params.put("uniqfield", "userid");
        params.put("filt", "y");
        params.put("priceStart", String.valueOf(priceStart));
        params.put("priceEnd", String.valueOf(priceEnd));
        params.put("beginPage", String.valueOf(pageNum));
        params.put("async", "true");
        params.put("asyncCount", "20");
        params.put("pageSize", "60");
        params.put("requestId", "zsayHtFZBwwXAPiQJJTcNQG3Scs5yAGcnyCFZDdcxTpMAtjQ");
        params.put("startIndex", String.valueOf(startIndex));
        params.put("pageName", "major");
        params.put("sessionId", "2b95821b804c466db34c7a3d908ae516");
        params.put("urlEncodeType", "NO");
        params.put("_bx-v", "1.1.20");

        Map<String, String> headers = new HashMap<>(1);
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.54");
        headers.put("Referer", "https://s.1688.com/");
        JSONObject response = HttpUtils.getResponse(REQUEST_PATH, headers, params, true);
        JSONObject dataOuter = response.getJSONObject("data");

        // 判断是否获取成功
        if ("ok".equals(dataOuter.getString("msg"))) {
            JSONObject dataInner = dataOuter.getJSONObject("data");
            JSONArray offerList = dataInner.getJSONArray("offerList");
            List<Offer> offers = new ArrayList<>(offerList.size());

            for (int i = 0, offerListSize = offerList.size(); i < offerListSize; i++) {
                Object o = offerList.get(i);
                JSONObject jsonObject = (JSONObject) o;
                JSONObject information = jsonObject.getJSONObject("information");

                Offer offer = new Offer();
                offer.detail = information.getString("brief");
                offer.simpleSubject = information.getString("simpleSubject");
                offer.url = information.getString("detailUrl");
                offer.img = jsonObject.getJSONObject("image").getString("imgUrl");

                System.out.println("第" + pageNum + "页，第" + i + "条数据解析完成");

                offers.add(offer);
            }

            startIndex += 20;

            return offers;
        } else {
            throw new NullPointerException("获取响应体失败");
        }
    }
}
